var express = require('express'),fs = require('fs');
var wechat = require('wechat');
var WechatAPI = require('wechat-api');
var OAuth = require('wechat-oauth');
var async = require('async');
var moment = require('moment');
var Model = require('../model');

var model = new Model();

var Message = model.Message;
var Fans = model.Fans;

moment.locale('zh_cn');

/*
 * Module dependencies
 */
/**
 * Expose routes
 */

module.exports = Routes;

/**
 * Defines routes for application
 *
 * @param {Express} app `Express` instance.
 * @api public
 */

function Routes (app) {

	var config = app.get('config');

	var router = express.Router();

	var weToken = {
		token: config.weixin.access.token,
		appid: config.weixin.appid,
		encodingAESKey: config.weixin.access.encodingAESKey
	}

	var appid = config.weixin.appid;
	var appsecret = config.weixin.appsecret;

	//获取access_token
	var api = new WechatAPI(appid, appsecret, function (callback) {
		// 传入一个获取全局token的方法
		fs.readFile('./data/access_token.txt', 'utf8', function (err, txt) {
			if (err) {
				return callback(err);
			}
			//access_token.txt 第一次必须有值否则要传一个空的json 字符串
			callback(null, JSON.parse(txt));
		});
	}, function (token, callback) {
		fs.writeFile('./data/access_token.txt', JSON.stringify(token), callback);
	});

	var oauthApi = new OAuth(appid, appsecret, function (openid, callback) {
		// 传入一个根据openid获取对应的全局token的方法
		fs.readFile('./data/oauth/'+ openid +':access_token.txt', 'utf8', function (err, txt) {
			if (err) {return callback(err);}
			callback(null, JSON.parse(txt));
		});
	}, function (openid, token, callback) {
		// 请将token存储到全局，跨进程、跨机器级别的全局，比如写到数据库、redis等
		// 这样才能在cluster模式及多机情况下使用，以下为写入到文件的示例
		// 持久化时请注意，每个openid都对应一个唯一的token!
		fs.writeFile('./data/oauth/'+ openid +':access_token.txt', JSON.stringify(token), callback);
	});

	//微信接入的url 消息处理路由
	router.all('/wechat', wechat(weToken,
		wechat.event(function (message, req, res, next) {
			//微信事件处理 首先查找用户
			Fans.findOne({ openid: message.FromUserName }).exec(function (err, fans) {
				//订阅
				if( message.Event == 'subscribe' ){
					//从微信接口读取用户信息直接入库
					api.getUser(message.FromUserName, function(err, wxfans) {
						if( fans ) {
						// 有粉丝 更新粉丝信息
							fans.subscribe = 1;
							fans.headimgurl = wxfans.headimgurl;
							fans.nickname = wxfans.nickname;
							fans.subscribe_time = wxfans.subscribe_time;
							fans.save(function(err,resu){})
						}
						else { //没有粉丝 创建粉丝入库

							Fans.findOne().sort({ unique_id: -1 }).exec(function (err, lastFans) {
								wxfans.unique_id =  (!lastFans)? 0: (lastFans.unique_id + 1),
								wxfans.created_at = moment().unix();
								Fans.create(wxfans, function(err, insertedFans){});
							})

						}
						res.reply('感谢关注！');
					});
				} //取消订阅
				else if ( message.Event == 'unsubscribe' ) {
					if(fans) {
						fans.subscribe = 0;
						fans.save(function(err,resu){})
					}
					res.reply('再见');
				}
			});
		})
	));


	//创建菜单 菜单内容写成本地文件
	router.get('/wechat/menu/create',  function(req, res){

		var menu = require('../data/menu.json');

		api.createMenu(menu, function(err, result){
			res.writeHead(200);
			if(err){
				console.log(err);
				res.end('change menu error!');
			}
			else{
				res.end('success!');
			}
		});

	});

	//提示关注 朋友圈转发页面
	router.get('/welcome',  function(req, res){
		res.render('welcome');
	});

	//ajax 滚动加载
	router.get('/loadmore',  function(req, res){
		console.log(req.query._id);

		Message.findById(req.query._id, function (err, firstMsg) {
			Message.find({ unique_id: { $lt: firstMsg.unique_id }}).populate('fans').sort({created_at:-1}).limit(15).exec(function(err, msgData){
				var msgData = JSON.stringify(msgData);
				res.writeHead(200);
				res.end(msgData);
			});
		});
		
	});

	//oauth认证身份回调页面
	router.get('/transfer',  function(req, res){
		//获取access_token 和open_id 到此结束
		oauthApi.getAccessToken(req.query.code, function (err, result) {
			console.log(result);
			//var accessToken = result.data.access_token;
			var openid = result.data.openid;

			//获取openid 查数据库
			Fans.findOne({ openid: openid }).exec(function (err, fans) {
				//数据库中不存在该用户 直接跳转到提示关注页面
				if( !fans ) {
					res.redirect('/welcome');
				}
				else{
					//用户信息存入session
					req.session.fans = fans;
					//回调到请求来源url
					res.redirect(req.query.return_url);
				}
			});
		});

	});


	// 访问公众号页面经过此处过滤
	router.use('/marryme', function(req, res, next) {
		/*
		var weixinAgentReg = /MicroMessenger/;

		if( !weixinAgentReg.test(req.headers['user-agent']) ){
			res.setHeader('content-type', 'text/html;charset=UTF-8');
			res.end('对不起，仅限微信内部访问网页');
			return ;
		}

		if( !req.session.fans ) {
			var return_url = req.originalUrl;
			// 没有通过身份认证 oauth 微信网页授权
			var oauthUrl = oauthApi.getAuthorizeURL('http://wechat.jiayu77.com/transfer?return_url='+return_url, '123', 'snsapi_base');
			//跳转到 https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect 获取code
			res.redirect(oauthUrl);
		}
		else {
			app.locals.fans = req.session.fans;
			next();
		}
		*/
		Fans.findOne({ openid: 'om92ixEH3EqcSdm_9ZDSJRzEoJss' }).exec(function (err, fans) {
			app.locals.fans = fans;
			next();
		})

	});


	router.get('/marryme/lovestory', function(req, res) {
		res.render('lovestory');
	});


	router.get('/marryme/blessing', function(req, res) {

		Message.find().populate('fans').sort({created_at:-1}).limit(15).exec(function(err, msg){
			Message.count({}, function (err, count) {
				res.render('blessing', { msgData: msg , msgCount: count, moment: moment});
			});
		});

	});

	router.get('/marryme/about', function(req, res) {
		res.writeHead(200);
		res.end('request ok!');
	});

	app.use(router);

}
